package com.example.app.util

import android.content.ClipDescription
import android.content.ContentResolver
import android.content.ContentUris
import android.content.ContentValues
import android.media.metrics.Event
import android.net.Uri
import android.provider.CalendarContract
import com.example.app.data.bean.CalendarEventInfo
import com.example.app.data.bean.CalendarInfo
import com.example.app.data.bean.routeTask.TaskItem
import java.util.TimeZone

var CALENDAR_ID = 1L
//更新日历事件
fun updateEventByEventId(
    eventId: Long,
    contentResolver: ContentResolver,
    title: String? = null,
    description: String? = null,
    dtStart: String? = null,
    dtEnd: String? = null,
) {
    try {
        var contentValues = ContentValues().apply {
            if (title != null) {
                put(CalendarContract.Events.TITLE, title)
            }
            if (description != null) {
                put(CalendarContract.Events.DESCRIPTION, description)
            }
            if (dtStart != null) {
                put(CalendarContract.Events.DTSTART, dtStart)
            }
            if (dtEnd != null) {
                put(CalendarContract.Events.DTEND, dtEnd)
            }
        }
        var uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId)
        var rows = contentResolver.update(
            uri,
            contentValues,
            null,
            null
        )
        myLog(rows, "更新event")
    } catch (e: Exception) {
        myLog(e.message.toString(), "更新event失败")
    }
}
//删除日历事件
fun cancelEventByEventId(eventId: Long, contentResolver: ContentResolver) {
    try {
        var uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId)
        var rows = contentResolver.delete(
            uri,
            null,
            null
        )
        myLog(rows, "删除event")
    } catch (e: Exception) {
        myLog(e.message.toString(), "删除event失败")
    }
}
//查询 reminder 通过 eventId
fun searchEventByEventId(eventId: Long, contentResolver: ContentResolver): CalendarEventInfo {
    var calendarEventInfo = CalendarEventInfo()
    calendarEventInfo.eventId = eventId
    var projection = arrayOf(
        CalendarContract.Events.DTEND,
        CalendarContract.Events.DTSTART,
        CalendarContract.Events.TITLE,
        CalendarContract.Events.DESCRIPTION,
        CalendarContract.Events.DELETED
    )
    var cur = contentResolver.query(
        CalendarContract.Events.CONTENT_URI,
        projection,
        "${CalendarContract.Events._ID}=?",
        arrayOf(eventId.toString()),
        null
    )

    if (cur != null) {
        while (cur.moveToNext()) {
            var titleIndex = cur.getColumnIndex(CalendarContract.Events.TITLE)
            var dtStartIndex = cur.getColumnIndex(CalendarContract.Events.DTSTART)
            var dtEndIndex = cur.getColumnIndex(CalendarContract.Events.DTEND)
            var descriptionIndex = cur.getColumnIndex(CalendarContract.Events.DESCRIPTION)
            var deletedIndex = cur.getColumnIndex(CalendarContract.Events.DELETED)
            if (titleIndex >= 0) {
                calendarEventInfo.title = cur.getString(titleIndex)
            }
            if (dtStartIndex >= 0) {
                calendarEventInfo.dtStart = cur.getString(dtStartIndex)
            }
            if (dtEndIndex >= 0) {
                calendarEventInfo.dtEnd = cur.getString(dtEndIndex)
            }
            if (descriptionIndex >= 0) {
                calendarEventInfo.description = cur.getString(descriptionIndex)
            }
            if (deletedIndex >= 0) {
                calendarEventInfo.deleted = cur.getString(deletedIndex)
            }
        }
    }
    return calendarEventInfo
}
//通过 calendarName 查询日历
fun searchCalendarsByCalendarName(
    calendarName: String,
    contentResolver: ContentResolver
): CalendarInfo {
    var calendarInfo = CalendarInfo(null, null)
    // 查询日历 , 看同名日历是否存在
    val projection = arrayOf(
        CalendarContract.Calendars._ID,
        CalendarContract.Calendars.NAME
        // 添加其他需要查询的字段...
    )
    //查询条件
    val selection = "${CalendarContract.Calendars.NAME} = ?"
    val selectionArgs = arrayOf(calendarName)
    //进行查询
    val cur = contentResolver.query(
        CalendarContract.Calendars.CONTENT_URI,
        projection,
        selection,
        selectionArgs,
        null
    )
    if (cur != null) {
        while (cur.moveToNext()) {
            //如果存在同名日历 , 则获取该日历的id
            var calendarIdIndex = cur.getColumnIndex(CalendarContract.Calendars._ID)
            var calendarNameIndex = cur.getColumnIndex(CalendarContract.Calendars.NAME)
            if (calendarIdIndex != null) {
                calendarInfo.calendarId = cur.getLong(calendarIdIndex)
            }

            if (calendarNameIndex != null) {
                calendarInfo.calendarName = cur.getString(calendarNameIndex)
            }
        }
    }
    return calendarInfo
}
//插入一个calendar
fun insertCalendar(contentResolver: ContentResolver, calendarName: String): Long? {
    var contentValues = ContentValues()
    contentValues.apply {
        put(CalendarContract.Calendars.NAME, calendarName)
    }
    val newCalendarUri: Uri? =
        contentResolver.insert(
            CalendarContract.Calendars.CONTENT_URI,
            contentValues
        )

    return newCalendarUri?.lastPathSegment?.toLongOrNull()
}
//查询所有event , 通过event , 查询和event关联的所有calendar
fun allCanlendarEvent(contentResolver: ContentResolver) {
    val eventProjection = arrayOf(
        CalendarContract.Events._ID,
        CalendarContract.Events.TITLE,
        CalendarContract.Events.DESCRIPTION,
        CalendarContract.Events.CALENDAR_ID
    )
    val eventSelection = null
    val eventSelectionArgs = null
    var eventCursor = contentResolver.query(
        CalendarContract.Events.CONTENT_URI,
        eventProjection,
        eventSelection,
        eventSelectionArgs,
        null
    )
    if (eventCursor != null) {
        do {
            //读取关联的 calendarId
            var calendarIdIndex =
                eventCursor.getColumnIndex(CalendarContract.Events.CALENDAR_ID)
            try {
                var eventCalendarId = eventCursor.getLong(calendarIdIndex)
                myLog(eventCalendarId.toString(), "eventCalendarId")
                contentResolver.query(
                    CalendarContract.Calendars.CONTENT_URI,
                    arrayOf(CalendarContract.Calendars.NAME),
                    "${CalendarContract.Calendars._ID}=?",
                    arrayOf(eventCalendarId.toString()),
                    null
                )?.use {
                    while (it.moveToNext()) {
                        var calendarNameIndex =
                            it.getColumnIndex(CalendarContract.Calendars.NAME)
                        if (calendarNameIndex >= 0) {
                            var eventCalendarName =
                                it.getString(calendarNameIndex)
                            try {
                                myLog(eventCalendarName, "eventCalendarName")
                            } catch (e: Exception) {
                                myLog(e.message.toString(), "eventCalendarName error")
                            }
                        }
                    }
                }
            } catch (e: Exception) {
            }
            //读取 event title
            var eventTitleIndex = eventCursor.getColumnIndex(CalendarContract.Events.TITLE)
            //读取 event description
            var eventDescriptionIndex =
                eventCursor.getColumnIndex(CalendarContract.Events.DESCRIPTION)
            try {
                if (eventTitleIndex >= 0) {
                    var eventTitle = eventCursor.getString(eventTitleIndex)
                    myLog(eventTitle, "eventTitle")
                }
                if (eventDescriptionIndex >= 0) {
                    var eventDescription = eventCursor.getString(eventDescriptionIndex)
                    myLog(eventDescription, "eventDescription")
                }
            } catch (e: Exception) {
            }
        } while (eventCursor.moveToNext())
    }
}
//向 calendar 插入一个 event 返回一个eventId
fun insertEventInCalendar(
    calendarId: Long = CALENDAR_ID,
    taskItem: TaskItem,
    contentResolver: ContentResolver
): Long? {
    var eventContentValues = ContentValues()
    eventContentValues.apply {
        put(CalendarContract.Events.CALENDAR_ID, calendarId)
        put(CalendarContract.Events.TITLE, taskItem.Title)
        put(CalendarContract.Events.DESCRIPTION, taskItem.Message)
        put(
            CalendarContract.Events.EVENT_TIMEZONE,
            TimeZone.getDefault().id
        )
        put(
            CalendarContract.Events.DTSTART,
            taskItem.ExpirationTime
        ) // 开始时间（当前时间）
        put(
            CalendarContract.Events.DTEND,
            taskItem.ExpirationTime
        ) // 结束时间（开始时间后一小时）
        put(CalendarContract.Events.ALL_DAY, 0) // 是否全天事件，这里设置为非全天事件
    }
    val eventUri: Uri? =
        contentResolver.insert(CalendarContract.Events.CONTENT_URI, eventContentValues)
    // 返回一个eventId
    return eventUri?.lastPathSegment?.toLongOrNull()
}
//向event 添加提醒
fun insertReminderByEventId(
    eventId: Long,
    contentResolver: ContentResolver,
): Long? {
    // 添加准时提醒
    var reminderValues = ContentValues()
    reminderValues.apply {
        put(CalendarContract.Reminders.MINUTES, 0) // 提醒时间：与事件结束时间一致
        put(
            CalendarContract.Reminders.METHOD,
            CalendarContract.Reminders.METHOD_DEFAULT
        ) // 提醒方式：警报
        put(
            CalendarContract.Reminders.EVENT_ID,
            eventId
        ) // 在插入事件后将此值替换为事件的实际ID
    }
    var reminderUri = contentResolver.insert(CalendarContract.Reminders.CONTENT_URI, reminderValues)
    return reminderUri?.lastPathSegment?.toLongOrNull()
}



